"""
python爬取网易云热歌榜歌曲

模块：
    requests   >>> pip install requests
    re
    os

- 数据来源：
    https://pvp.qq.com/web201605/js/herolist.json
"""
import requests
import os
import re

# 图片存储根路径
fileName = 'img/'

# 如果想要爬取其他榜单的内容，只需要更改请求 url 查询参数的id即可
url = 'https://pvp.qq.com/web201605/js/herolist.json'
# 请求头
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/54.0.2840.99 Safari/537.36 "
}


def save(hero_name, name, img_url):
    """保存皮肤"""
    filenames = f'{fileName}{hero_name}/'
    # 如果文件夹不存在，则创建文件
    if not os.path.exists(filenames):
        os.makedirs(filenames)

    image_content = requests.get(url=img_url, headers=headers).content
    with open(filenames + name + '.jpg', mode='wb') as f:
        f.write(image_content)
        print(name)


response = requests.get(url=url, headers=headers)
heros = response.json()
# print(heros)
for hero in heros:
    hero_id = hero['ename']  # 英雄id
    hero_name = hero['cname']  # 英雄名称
    index_url = f'https://pvp.qq.com/web201605/herodetail/{hero_id}.shtml'  # 英雄详情页
    response_1 = requests.get(url=index_url, headers=headers)
    response_1.encoding = response_1.apparent_encoding
    # 皮肤名字
    skin_name = re.findall('data-imgname="(.*?)">', response_1.text)[0]
    # 替换 replace 字符串高级方法
    # split 分割，返回一个列表
    skin_name = re.sub('&\d+', '', skin_name).split('|')
    for link in range(1, len(skin_name) + 1):
        link_url = f'https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/{hero_id}/{hero_id}-bigskin-{link}.jpg'
        link_name = skin_name[link - 1]
        # print(link_url, link_name)
        save(hero_name, link_name, link_url)
    break
